<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <!-- 组织架构的内容- 头部 -->
      <el-card class="tree-card">
        <!-- 放置结构内容 -->
        <tree-tools :tree-node="company" :is-root="true" @addDepts="addDepts" />

        <!-- 放置一个el-tree -->
        <el-tree
          :data="departs"
          :props="defaultProps"
          :default-expand-all="true"
        >
          <!-- 传入内容 插槽内容 会循环多次 有多少节点 循环多少次 -->
          <!-- 作用域插槽 slot-scope="obj" 接收传递给插槽的数据 data 每个节点的数据对象-->
          <tree-tools
            slot-scope="{ data }"
            :tree-node="data"
            @editDepts="editDepts"
            @addDepts="addDepts"
            @delDepts="getDepartments"
          />
        </el-tree>
        <!-- 放置新增弹层组件 -->
        <add-dept
          ref="addDept"
          :show-dialog.sync="showDialog"
          :tree-node="node"
          @addDepts="getDepartments"
        />
      </el-card>
    </div>
  </div>
</template>

<script>
import TreeTools from './components/tree-tools'
import AddDept from './components/add-dept'
import { getDepartments } from '@/api/departments'
import { tranListToTreeData } from '@/utils/index.js'

export default {
  components: { TreeTools, AddDept },
  data() {
    return {
      showDialog: false,
      company: {}, // 就是头部的数据结构
      defaultProps: {
        label: 'name'
      },
      departs: [],
      node: null, // 记录当前点击的节点
      loading: false
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    // 编辑部门节点
    editDepts(node) {
      // 首先打开弹层
      this.showDialog = true
      this.node = node // 赋值操作的节点
      // 应该在这里调用获取部门详情的方法
      this.$refs.addDept.getDepartDetail(node.id)
    },
    // 添加子部门的事件
    addDepts(node) {
      this.showDialog = true
      this.node = node
    },
    async getDepartments() {
      this.loading = true
      const result = await getDepartments()
      console.log(result)
      this.company = { name: result.companyName, manager: '负责人', id: '' }
      this.departs = tranListToTreeData(result.depts, '') // 需要将其转化成树形结构
      this.loading = false
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>

